extends Control

onready var vbox := $HSplitContainer/Panel/ScrollContainer/VBoxContainer
var player_deck : Deck
var button_group := ButtonGroup.new()
var selected_unit: Unit
	
func _ready():
	reload_all_units_from_disk()
	$HSplitContainer/Panel/ScrollContainer/VBoxContainer/UserNameLabel.text = Globals.current_user
	if ResourceLoader.exists(Globals.get_user_deck_file()):
		player_deck = Globals.get_user_deck()
	else:
		player_deck = Deck.new()

func get_units_list(type: String) -> Array:
	var dir := Directory.new()
	var arr := []
	var path : String = "res://Units/" + type
	if dir.open(path) == OK:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "" and file_name != "." and file_name != "..":
			arr.append(load(path + "/" + file_name))
			file_name = dir.get_next()
	return arr
	
func reload_all_units_from_disk():
	var u = Unit.new()
	for unit_type in u.type_string:
		var unit_list = get_units_list(unit_type)
		var node = vbox.get_node(unit_type +  "HBox")
		if node:
			add_units_to_node(node, unit_list)

func add_units_to_node(node : VBoxContainer, list: Array):
	for child in node.get_children():
		node.remove_child(child)
	for unit in list:
		var u = unit.instance()
		var cb = UnitButton.new()
		cb.text = u.unit_name
		cb.unit = u
		cb.icon = u.get_sprite()
		cb.expand_icon = true
		cb.toggle_mode = true
		cb.group = button_group
		cb.size_flags_horizontal = SIZE_FILL
		cb.size_flags_vertical = SIZE_FILL
		cb.connect("selected", self, "_on_cb_selected")
		node.add_child(cb)

func _on_cb_selected(unit: Unit):
	selected_unit = unit
	$"%AddToDeckCheckButton".pressed = player_deck.has_unit(unit)
	$"%TextureRect".texture = unit.get_sprite()


func _on_DoneButton_pressed():
	ResourceSaver.save(Globals.get_user_deck_file(), player_deck)


func _on_AddToDeckCheckButton_toggled(button_pressed):
	if button_pressed:
		player_deck.add_unit(selected_unit)
	else:
		player_deck.remove_unit(selected_unit)
